

<!DOCTYPE html>
<html lang="en" xmlns:v-on="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!-- 1.引入vue.js -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<!--使用Vue完成简易购物车案例-->
<div id="box">
    <table v-if = "book.length" border="1px" width="50%" height="450px" align="center" cellspacing="0">
        <thead><tr>
            <th>编号</th>
            <th>商品名称</th>
            <th>出版日期</th>
            <th>价格</th>
            <th>购买数量</th>
            <th>操作</th>
        </tr></thead>
        <tbody>
        <tr v-for="(item , index) in book"  align="center">
            <td>{{index + 1}}</td>
            <td>{{item.name}}</td>
            <td>{{item.date}}</td>
            <td>￥{{item.price}}</td>
            <td>
                <button v-on:click="minus(index)":disabled="item.count<=1">-</button>
                {{item.count}}
                <button @click="plus(index)">+</button>
            </td>
            <td>
                <button @click="shanchu(index)">移除</button>
            </td>
        </tr>
        <tr>
            <td colspan="6">
            总价格：￥{{totalPrice | showPrice}}
            </td>
        </tr>
        </tbody>
    </table>
</div>

</body>
<script>
    new Vue({
        el:"#box",
        data : {
            book : [
                {
                    name:"java编程",
                    date:"2020/9",
                    price: "98.00",
                    count: 1
                },
                {
                    name:"数据分析与数据原理",
                    date:"2019/2",
                    price:"39.00",
                    count: 1
                },
                {
                    name:"Hadoop权威指南",
                    date:"2019/10",
                    price: "59.00",
                    count: 1
                },
                {
                    name:"代码大全",
                    date:"2018/8",
                    price: "128.00",
                    count: 1
                }
            ]
        },
        computed: {
            totalPrice(){
                let totalprice = 0
                for(let i = 0;i < this.book.length; i++){
                    totalprice += this.book[i].count*this.book[i].price;
                }
                return totalprice;
            }
        },
        methods : {
            shanchu:function(index){
                this.book.splice(index, 1);
                for(let i = 0; i<this.book.length;i++) {
                    this.book[i].id = i + 1;
                }
            },
            minus:function(index){
                this.book[index].count -= 1
            },
            plus:function(index){
                this.book[index].count += 1
            }
        }
    })
</script>
</html>